import './index.css'
import {useStore} from "../store";
import {observer} from "mobx-react-lite";
import {useState} from "react";
import uuid from "react-uuid";

function Task() {

    const {taskStore} = useStore();

    function change(id, e) {
        taskStore.singleCheck(id, e.target.checked)
    }

    function allChange(e) {
        taskStore.allCheck(e.target.checked)
    }

    function del(id) {
        console.log(id)
        taskStore.delTask(id)
    }

    const [searchValue, setSearchValue] = useState('')

    function addTask(e) {
        if (e.keyCode === 13) {
            taskStore.addTask({
                id: uuid(), name: searchValue, isDone: false
            })
            setSearchValue('')
        }
    }

    return (<section className="todoapp">
        <header className="header">
            <h1>todos</h1>
            <input
                className="new-todo"
                autoFocus
                autoComplete="off"
                placeholder="What needs to be done?"
                value={searchValue}
                onKeyUp={addTask}
                onChange={(e) => setSearchValue(e.target.value)}
            />
        </header>
        <section className="main">
            <input
                id="toggle-all"
                className="toggle-all"
                type="checkbox"
                checked={taskStore.isAll}
                onChange={allChange}
            />
            <label htmlFor="toggle-all"></label>
            <ul className="todo-list">
                {taskStore.list.map(item => (<li className={item.isDone ? "todo completed" : "todo"} key={item.id}>
                    <div className="view">
                        <input className="toggle" type="checkbox" onChange={(e) => change(item.id, e)}
                               checked={item.isDone}/>
                        <label>{item.name}</label>
                        <button className="destroy" onClick={() => del(item.id)}></button>
                    </div>
                </li>))}
            </ul>
        </section>
        <footer className="footer">
            <span className="todo-count">
                任务总数：{taskStore.list.length} 已完成：{taskStore.list.filter(n => n.isDone).length}
            </span>
        </footer>
    </section>)
}

export default observer(Task)